#include <QDebug>
#include <QTimer>
#include <QUdpSocket>
#include <QDateTime>

#include "UDP_RTAudio.h"

UDP_RTAudio::UDP_RTAudio(void) : UDPHelper(NULL)
{
    setUI();
    pTimer = new QTimer(this);

    connect(pTimer, &QTimer::timeout, this, &UDP_RTAudio::timer10ms);
    connect(playBtn, &QPushButton::clicked, this, &UDP_RTAudio::playOrStop);

    pAudioFmt = new QAudioFormat();
    setAudioFmt();

    db_dataCnt = 0;
    qDebug() << "Create UDP_RTAudio" << endl;
}

UDP_RTAudio::~UDP_RTAudio()
{
    delete pTimer;
    this->destroyUI();
}

void UDP_RTAudio::timer10ms()
{

    if (pAudioOut && pAudioOut->state() != QAudio::StoppedState &&
        pAudioOut->state() != QAudio::SuspendedState)
    {
        // streamOut->write(tmpBuffer);
        // streamOut->write(tmpBuffer,size);
        // tmpBuffer.clear();
        // tmpbuff = tmpBuff.mid(audioOutput->periodSize());
    }
}

void UDP_RTAudio::readData()
{
    QByteArray array;
    QHostAddress address;
    quint16 port;
    array.resize(recSocket->bytesAvailable());
    recSocket->readDatagram(array.data(), array.size(), &address, &port);

    QDateTime time = QDateTime::currentDateTime(); //获取当前时间
    int timeT = time.toTime_t();                   //将当前时间转为时间戳
    qDebug() << array.data() << endl;
    qDebug() << ++db_dataCnt << "   " << array.size() << "   " << time  << endl;
    return;
}

void UDP_RTAudio::playOrStop()
{
    if (playBtn->text() == tr("Play"))
    {
        playBtn->setText(tr("Stop"));
        pTimer->start(10);
        qDebug() << "Start Play" << endl;
    }
    else
    {
        pTimer->stop();
        playBtn->setText(tr("Play"));
        qDebug() << "Stop Play" << endl;
    }
}

void UDP_RTAudio::setAudioFmt()
{
    pAudioFmt->setSampleRate(16000);
    pAudioFmt->setChannelCount(1);
    pAudioFmt->setSampleSize(16);
    pAudioFmt->setCodec("audio/pcm");
    pAudioFmt->setByteOrder(QAudioFormat::LittleEndian);
    pAudioFmt->setSampleType(QAudioFormat::UnSignedInt);
    QAudioDeviceInfo info = QAudioDeviceInfo::defaultOutputDevice();
    if (!info.isFormatSupported(*pAudioFmt))
    {
        qDebug() << "default format not supported try to use nearest";
        *pAudioFmt = info.nearestFormat(*pAudioFmt);
    }
    pAudioOut = new QAudioOutput(*pAudioFmt, this);
}

void UDP_RTAudio::setUI()
{
    playBtn = new QPushButton(this);
    playBtn->setEnabled(true);
    playBtn->setText("Play");
    playBtn->setGeometry(350, 20, 80, 30);
}

void UDP_RTAudio::destroyUI()
{
    delete playBtn;
    qDebug() << "destroy UDP_RTAudio UI" << endl;
}
